package com.ququ.syb.application.service;

import com.ququ.common.result.Result;
import com.ququ.common.utils.MD5Util;
import com.ququ.syb.application.mongo.ApplicationDao;
import com.ququ.syb.application.redis.RedisDao;
import com.ququ.syb.common.constant.RedisKeyConstant;
import com.ququ.syb.common.pojo.Application;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;

@Service
public class ApplicationService {
    @Autowired
    private ApplicationDao applicationDao;
    @Autowired
    private RedisDao redisDao;

    public Result<Application> getApplication(String appcode){
        Application application = applicationDao.findAccessApplicationByCode(Integer.parseInt(appcode));
        if (application == null)
            return new Result<>(-1,"无此应用代码");
        else
            return new Result<>(application);
    }


    public Result<String> getApplicationKey(String appcode){
        Application application = applicationDao.findAccessApplicationByCode(Integer.parseInt(appcode));
        if (application == null)
            return new Result<>(-1,"无此应用代码");
        else
            return new Result<>(application.getPrivatekey().substring(8,24));
    }

    public Result<Application> addApplication(String appcode,String appname,String homepage, Integer allowpay, Integer allowwithdraw){
        Jedis jedis = redisDao.getJedis();
        try {
            Application application = null;
            if (StringUtils.isBlank(appcode))
                appcode = jedis.incr(RedisKeyConstant.LAST_APP_CODE).toString();
            else {
                application = applicationDao.findAccessApplicationByCode(Integer.parseInt(appcode));
                if (application != null)
                    return new Result<>(-1,"应用代码"+appcode+"已存在");
            }
            application = new Application();
            application.setCode(Integer.parseInt(appcode));
            application.setName(appname);
            application.setHomepage(homepage);
            application.setAllowpay(allowpay==null?1:allowpay);
            application.setAllowwithdraw(allowwithdraw==null?1:allowwithdraw);
            application.setPrivatekey(MD5Util.md5(RandomStringUtils.randomAlphanumeric(32)));
            application.setPassword(MD5Util.md5(RandomStringUtils.randomAlphanumeric(32)));
            application.setStatus(1);
            application = applicationDao.save(application);
            return new Result<>(application);
        }finally {
            redisDao.close(jedis);
        }
    }

    public Result<List<Application>> listApplication(){
        return new Result<>(applicationDao.findAll());
    }

}
